package com.beiding.dao.impl;

import com.beiding.dao.GenerationDao;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Set;

@Repository
public class GenerationDaoImpl implements GenerationDao {


    private String prevGeneration;

    private String concurrentGeneration="-";

    private RedisTemplate<String, String> redisTemplate;

    private SetOperations<String, String> setOperations;

    private GenerationManager generationManager;

    public GenerationDaoImpl(RedisTemplate<String, String> redisTemplate, GenerationManager generationManager) {
        this.redisTemplate = redisTemplate;
        setOperations = redisTemplate.opsForSet();
        this.generationManager = generationManager;
    }

    @Override
    public void addTemp(List<String> ids) {
        ids.forEach(this::addTemp);
    }

    @Override
    public void addTemp(String id) {
        setOperations.add(concurrentGeneration, id);
    }

    @Override
    public void removeTemp(String id) {

        //移除两代中的公共资源

        Long remove = setOperations.remove(concurrentGeneration, id);

        if (remove > 0) {
            return;
        }else {
            setOperations.remove(prevGeneration, id);
        }
    }

    @Override
    public Set<String> alternate(int intervalGenerationToRemove) {

        long generation = generationManager.generation();

        prevGeneration = concurrentGeneration;

        concurrentGeneration = generationManager.getPrefix() + generation;

        long removeG = generation - intervalGenerationToRemove;

        Set<String> r = setOperations.members(generationManager.getPrefix()+removeG);

        redisTemplate.delete(generationManager.getPrefix() + removeG);

        return r;
    }



}
